-module(role_api).

-export([
	lookup/2
	,lookup/3
]).

-export([
	push_login/1
]).


-include("common.hrl").
-include("role.hrl").
-include("link.hrl").
-include("pb.hrl").


%%%===================================================================
%%% API functions
%%%===================================================================

%% -> {error, not_found} | {error, self_call} | {ok, record()}
lookup(by_pid, Pid) ->
	lookup(by_pid, Pid, to_role);
lookup(by_id, Rid) when is_integer(Rid) ->
	lookup(by_id, Rid, to_role);
lookup(by_name, Name) ->
	lookup(by_name, Name, to_role).

%% -> {error, not_found} | {error, self_call} | {ok, Rtn}
lookup(by_pid, Pid, ReturnType) when is_atom(ReturnType) ->
	case role:convert(ReturnType, Pid) of
		{ok, R} -> {ok, node(), R};
		{error, Reason} -> {error, Reason}
	end;
lookup(by_pid, Pid, ReturnType) ->
	case role:element(Pid, ReturnType) of
		{ok, R} -> {ok, node(), R};
		{error, Reason} -> {error, Reason}
	end;
lookup(by_id, Rid, ReturnType) when is_atom(ReturnType) ->
	case global:whereis_name({role, Rid}) of
		undefined -> {error, not_found};
		Pid ->
			case role:convert(ReturnType, Pid) of
				{ok, R} -> {ok, node(Pid), R};
				Else -> Else
			end
	end;
lookup(by_id, Rid, ReturnType) ->
	case global:whereis_name({role, Rid}) of
		undefined -> {error, not_found};
		Pid ->
			case role:element(Pid, ReturnType) of
				{ok, R} -> {ok, node(Pid), R};
				Else -> Else
			end
	end.


%%%===================================================================
%%% 消息推送
%%%===================================================================

push_login(#role{rid = Rid}) ->
	util_role:pack_send(?p_role_login_ok, {Rid}).
